//
//  ChatViewController.swift
//  EasyChat
//
//  Created by it-go-0367 on 2021/12/7.
//

import UIKit

class ChatViewController: UIViewController {
    /** 顶部视图*/
    let topView : UIView = UIView.init()
    let profileView : UIImageView = UIImageView.init() //头像
    let nickNameLabel : UILabel = UILabel.init() //昵称
    let stateLabel : UILabel = UILabel.init() //状态
    let cameraImage : UIImageView = UIImageView.init()
    let moreImage : UIImageView = UIImageView.init()
    /** 内容视图*/
    let mainView : UIView = UIView.init()
    let searchField : UserDefineTextField = UserDefineTextField.init() //搜索框
    let messageTable : UITableView = UITableView.init() //消息列表
    /** 消息列表*/
    //var messageList : [EasyChatC2CResponse] = [EasyChatC2CResponse]()  //消息的集合
    //var messageCount : [Int : Int] = [:]  //对应好友的消息的数量映射
    ///是加上来自每个好友的消息都是个数组
    //var mateMessageList : [Int : [EasyChatC2CResponse]] = [:]
    ///未读消息数量还是要单独弄过来备用
    var mateMessageUnReceive : [Int : Int] = [:]
    ///聊天好友顺序
    var mateSort : [Int] = []
    ///有新消息来的回调
    var catchNewMessage : (()->Void)?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        let meInfo = AppDelegate.userInfos[AppDelegate.meInfo.number]
        self.tabBarItem = UITabBarItem.init(title: "消息", image: UIImage.init(named: "chat_unsel")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage.init(named: "chat_sel")?.withRenderingMode(.alwaysOriginal))
        self.view.backgroundColor = UIColor.init(red: 0.07, green: 0.64, blue: 1, alpha: 1)
        initData()  //初始化数据
        /** 顶部视图*/
        topView.frame = CGRect.init(x: 0, y: stateRegionHeight, width: screenWidth, height: 92-stateRegionHeight)
        topView.backgroundColor = UIColor.init(red: 0.07, green: 0.64, blue: 1, alpha: 1)
        self.view.addSubview(topView)
        /// profileView 头像离上边界距离大约为5pt，离左边界的距离大约是15pt，长宽相等约32pt
        profileView.frame = CGRect.init(x: 15, y: 5, width: 32, height: 32)
        profileView.image = UIImage.init(named: meInfo!.matePhote)
        profileView.layer.masksToBounds = true
        profileView.layer.cornerRadius = 16
        topView.addSubview(profileView)
        /// nickNameLabel距离头像10pt，Y轴大约比头像高了1pt，16号字体
        nickNameLabel.frame = CGRect.init(x: profileView.frame.maxX+10, y: 6, width: 10, height: 16)
        nickNameLabel.text = meInfo!.mateName
        nickNameLabel.sizeToFit()
        nickNameLabel.font = UIFont.systemFont(ofSize: 16)
        nickNameLabel.textAlignment = .left
        nickNameLabel.textColor = UIColor.white
        topView.addSubview(nickNameLabel)
        /// stateLabel距离左侧10pt，距离上边界5pt，10pt字体
        stateLabel.frame = CGRect.init(x: profileView.frame.maxX+10, y: nickNameLabel.frame.maxY-2, width: 10, height: 10)
        stateLabel.text = meInfo?.mateState.rawValue
        stateLabel.sizeToFit()
        stateLabel.font = UIFont.systemFont(ofSize: 10)
        stateLabel.textAlignment = .left
        stateLabel.textColor = UIColor.white
        topView.addSubview(stateLabel)
        /// cameraImage
        cameraImage.frame = CGRect.init(x: screenWidth-(19*4), y: topView.frame.height-13-19, width: 20, height: 20)
        cameraImage.image = UIImage.init(named: "chat_camera")
        cameraImage.isUserInteractionEnabled = true
        let cameraRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(cameraHandler))
        cameraImage.addGestureRecognizer(cameraRecognizer)
        topView.addSubview(cameraImage)
        ///moreImage
        moreImage.frame = CGRect.init(x: screenWidth-(19*2), y: topView.frame.height-13-19, width: 20, height: 20)
        moreImage.image = UIImage.init(named: "chat_more")
        moreImage.isUserInteractionEnabled = true
        let moreRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(moreHandler))
        moreImage.addGestureRecognizer(moreRecognizer)
        topView.addSubview(moreImage)
        /** 内容视图*/
        mainView.frame = CGRect.init(x: 0, y: topView.frame.maxY, width: screenWidth, height: safeScreenHeight)
        mainView.backgroundColor = UIColor.white
        self.view.addSubview(mainView)
        /// searchField
        searchField.frame = CGRect.init(x: 16, y: 8, width: screenWidth-16-16, height: 36)
        searchField.backgroundColor = UIColor.init(red: 0.94, green: 0.95, blue: 0.97, alpha: 1)
        searchField.layer.masksToBounds = true
        searchField.layer.cornerRadius = 18
        searchField.placeholder = "搜索"
        mainView.addSubview(searchField)
        /// messageTable
        messageTable.frame = CGRect.init(x: 0, y: searchField.frame.maxY+8, width: screenWidth, height: mainView.frame.height-searchField.frame.maxY-8)
        messageTable.tableFooterView = UIView.init(frame: CGRect.zero)
        messageTable.delegate = self
        messageTable.dataSource = self
        mainView.addSubview(messageTable)
        EasyChatSocketTool.instance.setNewMessageColsure { [self] value in
            let responses : [NSDictionary] = value["responses"] as! [NSDictionary]
            //获取到消息类型
            let messageType : Int = value["responseType"] as! Int
            switch messageType {
            case 2:
                c2cResponseHandler(responses: responses)
            case 7:
                groupResponseHandler(responses: responses)
            default:
                print("未知消息类型")
            }
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @objc func cameraHandler() {
        print("cameraHandler")
    }
    
    @objc func moreHandler() {
        print("moreHandler")
    }
    
    func setCatchNewMessage(colsure : @escaping (()->Void)) {
        catchNewMessage = colsure
    }
    
    func initData() {
        let message1 = EasyChatC2CResponse.init()
        message1.content = "郑州航空航天管理学院"
        message1.fromNumber = 4141
        message1.toNumber = 9949
        message1.dateTime = "2021-12-25 20:19:25"
        ChatMessageStock.instance.addC2CResponse(c2cResponse: message1)
        mateMessageUnReceive[4141] = 1
        mateSort.append(4141)
        let message2 = EasyChatC2CResponse.init()
        message2.content = "郑州轻工业大学"
        message2.fromNumber = 9949
        message2.toNumber = 4141
        message2.dateTime = "2021-12-25 20:19:50"
        ChatMessageStock.instance.addC2CResponse(c2cResponse: message2)
        mateMessageUnReceive[9949] = 1
        mateSort.append(9949)
        let group1 = EasyChatGroupResponse.init()
        group1.groupID = 3
        group1.fromNumber = 9949
        group1.content = "欢迎加入333软件创新实验室☕️"
        group1.dateTime = "2021-12-25 20:19:50"
        ChatMessageStock.instance.addGroupResponse(groupResponse: group1)
        mateMessageUnReceive[group1.groupID] = 1
        mateSort.append(group1.groupID)
    }
    
    /** 私聊消息的处理函数*/
    func c2cResponseHandler(responses : [NSDictionary]) {
        for response in responses {
            let singleRespnose = convertC2CResponse(info: response)
            if mateMessageUnReceive[singleRespnose.fromNumber] == nil {
                //来自这个好友的消息是第一次来，直接向容器中丢就可以了
                mateMessageUnReceive[singleRespnose.fromNumber] = 1
            }else {
                //来自这个好友的消息之前有过了，需要替换掉之前的消息，把新消息的预览放倒最前面
                mateMessageUnReceive[singleRespnose.fromNumber]=mateMessageUnReceive[singleRespnose.fromNumber]!+1
            }
            mateSort.append(singleRespnose.fromNumber)
            ChatMessageStock.instance.addC2CResponse(c2cResponse: singleRespnose)
            //推送个通知过来
            AppCheck.instance.pushCommonNotify(message: singleRespnose.content, fromNumber: singleRespnose.fromNumber)
        }
        //通知一下其他VIew
        if catchNewMessage != nil {
            catchNewMessage!()
        }
        //重新加载一下表格
        DispatchQueue.main.async {
            self.messageTable.reloadData()
        }
    }
    
    /** 群聊消息的处理函数*/
    func groupResponseHandler(responses : [NSDictionary]) {
        for response in responses {
            let singleRespnose = convertGroupResponse(info: response)
            if mateMessageUnReceive[singleRespnose.groupID] == nil {
                //来自此群组的消息是第一次来，直接向容器中丢就可以了
                mateMessageUnReceive[singleRespnose.groupID] = 1
            }else {
                //来自此群组的消息之前有过了，需要替换掉之前的消息，把新消息的预览放倒最前面
                mateMessageUnReceive[singleRespnose.groupID]=mateMessageUnReceive[singleRespnose.groupID]!+1
            }
            mateSort.append(singleRespnose.groupID)
            ChatMessageStock.instance.addGroupResponse(groupResponse: singleRespnose)
            //推送个通知过来
            AppCheck.instance.pushGroupNotify(message: singleRespnose.content, groupID: singleRespnose.groupID, fromID: singleRespnose.fromNumber)
        }
        //通知一下其他VIew
        if catchNewMessage != nil {
            catchNewMessage!()
        }
        //重新加载一下表格
        DispatchQueue.main.async {
            self.messageTable.reloadData()
        }
    }
    
    /** 私聊消息响应的转换函数*/
    func convertC2CResponse(info : NSDictionary) -> EasyChatC2CResponse {
        let result = EasyChatC2CResponse.init()
        result.fromNumber = info.object(forKey: "fromNumber") as! Int
        result.toNumber = info.object(forKey: "toNumber") as! Int
        result.content = info.object(forKey: "content") as! String
        result.dateTime = info.object(forKey: "dateTime") as! String
        return result
    }
    
    /** 群聊消息响应的转换函数*/
    func convertGroupResponse(info : NSDictionary) -> EasyChatGroupResponse{
        let result = EasyChatGroupResponse.init()
        result.fromNumber = info.object(forKey: "fromNumber") as! Int
        result.content = info.object(forKey: "content") as! String
        result.dateTime = info.object(forKey: "dateTime") as! String
        return result
    }
}

extension ChatViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ChatMessageStock.instance.mateMessageList.count
    }
    
    /** 返回指定的列表项*/
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = MessageTableViewCell.init(style: .default, reuseIdentifier: "reuse")
        let message = ChatMessageStock.instance.mateMessageList[mateSort[indexPath.row]]?.last
        cell.setMessageItem(info: message!, msgcount: mateMessageUnReceive[mateSort[indexPath.row]]!)
        //cell.setMessageItem(info: message!, msgcount: mateMessageUnReceive[mateSort[indexPath.row]]!)
        return cell;
    }
    
    /** 列表项的高度*/
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    
    /** 列表项的点击事件*/
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let fromNumber : Int = mateSort[indexPath.row]
        ///清空未读标记
        mateMessageUnReceive[fromNumber] = 0
        DispatchQueue.main.async {
            self.messageTable.reloadData()
        }
        ///跳转到聊天页面
        if fromNumber < 1000 {  //群聊
            let fromGroup = AppDelegate.groupInfos[fromNumber]!
            let detailVC = ChatDetailViewController.init(groupInfo: fromGroup, bindVC: self)
            self.navigationController?.pushViewController(detailVC, animated: true)
        }else {  //私聊
            let fromMate = AppDelegate.userInfos[fromNumber]!
            let detailVC = ChatDetailViewController.init(mateInfo: fromMate, bindVC: self)
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
}
